package com.xbongbong.crm.abstracts;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.crm.help.FineClueHelp;
import com.xbongbong.crm.service.SearchCustomerService;
import com.xbongbong.paas.constant.MessageConstant;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.PaasFormExplainEntity;
import com.xbongbong.paas.domain.entity.PaasMenuEntity;
import com.xbongbong.paas.domain.entity.ext.PaasFormDataEntityExt;
import com.xbongbong.paas.domain.entity.ext.PaasFormEntityExt;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.FlowStatusEnum;
import com.xbongbong.paas.enums.PlatFormEnum;
import com.xbongbong.paas.enums.UnitEnum;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.field.LinkListPojo;
import com.xbongbong.paas.help.CloudCodeHelp;
import com.xbongbong.paas.help.FormDataFormExplainHelper;
import com.xbongbong.paas.help.OwnerAndCoUserHelp;
import com.xbongbong.paas.model.PaasAppModel;
import com.xbongbong.paas.model.PaasFormExplainModel;
import com.xbongbong.paas.model.PaasFormModel;
import com.xbongbong.paas.model.PaasMenuModel;
import com.xbongbong.paas.pojo.ButtonPojo;
import com.xbongbong.paas.pojo.DataDetailPojo;
import com.xbongbong.paas.pojo.DetailTabPojo;
import com.xbongbong.paas.pojo.FormTitlePoJo;
import com.xbongbong.paas.pojo.HandelDetailPojo;
import com.xbongbong.paas.pojo.SummaryDataPoJo;
import com.xbongbong.paas.pojo.WorkFlowPojo;
import com.xbongbong.paas.service.DetailTabConfigService;
import com.xbongbong.paas.service.LinkListService;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.thread.TransmittableThreadLocalUtil;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.wrap.UserVO;
import com.xbongbong.paas.util.ExplainUtil;
import com.xbongbong.paas.util.FormDataUtil;
import com.xbongbong.parent.abstracts.AbstractBusinessDetailTopInfoService;
import com.xbongbong.parent.explain.FormDataDetailFormExplainHandleName;
import com.xbongbong.parent.parse.data.FormDataGetAnalysisDataHelp;
import com.xbongbong.pro.appdetail.pojo.MobileDetailScriptPojo;
import com.xbongbong.pro.appdetail.pojo.MobileDetailSpecialInfoPojo;
import com.xbongbong.pro.appdetail.pojo.MobileDetailStatusPojo;
import com.xbongbong.pro.enums.DistributorMarkEnum;
import com.xbongbong.pro.enums.SaasMarkEnum;
import com.xbongbong.pro.enums.errorcodes.BuinessDefaultErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.form.pojo.TopPermissionsPoJo;
import com.xbongbong.pro.formdata.pojo.dto.FormDataDetailDTO;
import com.xbongbong.pro.formdata.pojo.vo.MobileFormCommonDetailVO;
import com.xbongbong.pro.formexplain.pojo.dto.HandlerExplainDTO;
import com.xbongbong.pro.formexplain.pojo.vo.HandlerExplainVO;
import com.xbongbong.pro.permission.pojo.dto.VerifyViewPermissionDTO;
import com.xbongbong.pro.service.toolbox.data.ProFormDataHelp;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.constant.TabConstant;
import com.xbongbong.saas.enums.BusinessDetailButtonEnum;
import com.xbongbong.saas.enums.BusinessDetailTabEnum;
import com.xbongbong.saas.enums.DetailTabEnum;
import com.xbongbong.saas.enums.MobileDetailBottomOperationEnum;
import com.xbongbong.saas.enums.RedundantTemplateTypeEnum;
import com.xbongbong.saas.enums.SaasButtonEnum;
import com.xbongbong.saas.enums.WorkFlowEnum;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.CustomerManagementEnum;
import com.xbongbong.saas.help.LabelHelp;
import com.xbongbong.saas.service.toolbox.help.AttrDecimalPrecisionHelper;
import com.xbongbong.saas.service.toolbox.help.UserTeamHelp;
import com.xbongbong.sys.domain.entity.UserEntity;
import com.xbongbong.sys.help.ProPermissionHelp;
import com.xbongbong.sys.model.UserModel;
import com.xbongbong.util.ContractCompareUtil;
import com.xbongbong.util.NameUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author 吴峰
 * @date 2022/02/11 10:02
 */
@Component
public abstract class AbstractCrmDetailTopInfoService extends AbstractBusinessDetailTopInfoService<PaasFormEntityExt, PaasFormDataEntityExt> {

    private static final Logger LOGGER = LoggerFactory.getLogger(AbstractCrmDetailTopInfoService.class);
    @Resource
    private LabelHelp labelHelp;
    @Resource
    private ProFormDataHelp proFormDataHelp;
    @Resource
    private PaasFormModel paasFormModel;
    @Resource
    private UserTeamHelp userTeamHelp;
    @Resource
    private CloudCodeHelp cloudCodeHelp;
    @Resource
    private LinkListService linkListService;
    @Resource
    private DetailTabConfigService detailTabConfigService;
    @Resource
    private PaasAppModel paasAppModel;
    @Resource
    private PaasFormExplainModel paasFormExplainModel;

    @Resource
    private PaasMenuModel paasMenuModel;
    @Resource
    private FormDataFormExplainHelper formDataFormExplainHelper;
    @Resource
    private OwnerAndCoUserHelp ownerAndCoUserHelp;
    @Resource
    private FormDataDetailFormExplainHandleName formDataDetailFormExplainHandleName;
    @Resource
    private SearchCustomerService searchCustomerService;
    @Resource
    private FineClueHelp fineClueHelp;
    @Resource
    private FormDataGetAnalysisDataHelp formDataGetAnalysisDataHelp;
    @Resource
    private ContractCompareUtil contractCompareUtil;
    @Resource
    private UserModel userModel;


    @Override
    public List<ButtonPojo> handleDetailButton(FormDataDetailDTO formDataDetailDTO, HandelDetailPojo handelDetailPojo, PaasFormDataEntityExt paasFormDataEntityExt, Map<String, FieldAttrEntity> explainMap) throws XbbException {
        String corpid = formDataDetailDTO.getCorpid();
        Integer businessType = handelDetailPojo.getBusinessType();
        List<ButtonPojo> buttonPojoList = handelDetailPojo.getButtonPojoList();
        UserVO userVO = handelDetailPojo.getLoginUser();
        List<BusinessDetailButtonEnum> buttonEnumList = BusinessDetailButtonEnum.getByBusinessTypeAndPermission(businessType, userVO.getPermSet());
        VerifyViewPermissionDTO verifyViewPermissionDTO = new VerifyViewPermissionDTO(userVO, paasFormDataEntityExt);
        boolean perTag = commonPermissionHelp.checkEditPermissionWithoutShareEdit(formDataDetailDTO, verifyViewPermissionDTO, explainMap);

        for (BusinessDetailButtonEnum buttonEnum : buttonEnumList) {
            ButtonPojo buttonPojo = new ButtonPojo();
            SaasButtonEnum saasButtonEnum = buttonEnum.getAnEnum();
            if (!perTag && Objects.equals(SaasButtonEnum.EDIT.getAttr(), saasButtonEnum.getAttr())) {
                continue;
            }
            BeanUtil.copyProperties(saasButtonEnum, buttonPojo);
            buttonPojo.setLinkBusinessType(buttonEnum.getLinkBusinessType());
            buttonPojoList.add(buttonPojo);
            if (Objects.equals(buttonEnum.getAnEnum().getAttr(), SaasButtonEnum.CONTRACT_COMPARE.getAttr()) && !contractCompareUtil.showCompareButton(formDataDetailDTO.getCorpid(), formDataDetailDTO.getLoginUser().getPermSet(), userVO.getUserId())) {
                continue;
            }
        }
        cloudCodeHelp.setCloudCodeDetailButton(corpid, userVO.getDynamicPermSet(), paasFormDataEntityExt.getAppId(), paasFormDataEntityExt.getFormId(), businessType, buttonPojoList, formDataDetailDTO.getPlatform());
        return buttonPojoList;
    }


    @Override
    public HandlerExplainVO handleExplain(List<FieldAttrEntity> explainList, PaasFormEntityExt formEntity, PaasFormDataEntityExt paasFormDataEntityExt, HandlerExplainDTO handlerExplainDTO) throws XbbException {
        handlerExplainDTO.setExplainList(explainList);
        ownerAndCoUserHelp.getOwnerIdAndCoUserId(handlerExplainDTO, handlerExplainDTO.getSaasMark(), handlerExplainDTO.getBusinessType(), paasFormDataEntityExt, new HashMap<>(), DelEnum.NORMAL.getDel());
        handlerExplainDTO.setFormData(paasFormDataEntityExt.getData());
        return formDataDetailFormExplainHandleName.handleExplain(explainList, formEntity, paasFormDataEntityExt, handlerExplainDTO);
    }

    @Override
    public List<WorkFlowPojo> webHandleDetailWorkFlow(HandelDetailPojo handelDetailPojo, PaasFormEntityExt formEntity, PaasFormDataEntityExt formData) throws XbbException {
        Integer businessType = handelDetailPojo.getBusinessType();
        UserVO userVO = handelDetailPojo.getLoginUser();
        Set<String> permSet = userVO.getPermSet();
        List<WorkFlowEnum> workFlowEnumList = WorkFlowEnum.getByBusinessTypeAndPermission(businessType, permSet);
        List<WorkFlowPojo> workFlowPojoList = new ArrayList<>();
        String corpid = userVO.getCorpid();
        Map<String,Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        // 获取对应businessType的alias
        List<String> aliasIn = new ArrayList<>();
        for (WorkFlowEnum workFlowEnum : workFlowEnumList) {
            if (Objects.isNull(workFlowEnum.getBusinessType())) {
                continue;
            }
            aliasIn.add(XbbRefTypeEnum.getByCode(workFlowEnum.getBusinessType()).getAlias());
        }
        param.put("corpid", corpid);
        param.put("aliasIn", aliasIn);
        param.put("del", DelEnum.NORMAL.getDel());
        param.put("distributorMark", DistributorMarkEnum.OTHER.getCode());
        List<PaasMenuEntity> paasMenuEntities = paasMenuModel.findEntitys(param);
        // 记录businessType与menuName的关系
        Map<Integer, String> paasBusinessTypeToName = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        paasMenuEntities.forEach(item-> paasBusinessTypeToName.put(XbbRefTypeEnum.getByAlias(item.getAlias()).getCode(),item.getName()));
        for (WorkFlowEnum workFlowEnum : workFlowEnumList) {
            WorkFlowPojo workFlowPojo = new WorkFlowPojo();
            BeanUtil.copyProperties(workFlowEnum, workFlowPojo);
            NameUtil.changeValue(paasBusinessTypeToName, workFlowPojo);
            workFlowPojoList.add(workFlowPojo);
        }
        List<LinkListPojo> linkList = JSONArray.parseArray(formEntity.getAssociationList(), LinkListPojo.class);
        workFlowPojoList.addAll(linkListService.getCommonButton(linkList, formData.getDel(), handelDetailPojo.getLoginUser(), formData.getAppId(), formData.getFormId(), handelDetailPojo.getBusinessType(), formEntity.getSaasMark(), corpid));
        return workFlowPojoList;
    }


    /**
     * 判断团队内是否有操作人数据权限内的人员，用于回退公海池按钮显隐判断
     *
     * @param data 表单数据data
     * @param loginUser 操作人
     * @return true:有  false:无
     */
    protected boolean checkCanBackPublic(JSONObject data, UserVO loginUser){
        UserEntity userEntity = new UserEntity();
        BeanUtil.copyProperties(loginUser, userEntity);
        //判断当前数据的团队内是否有操作人的数据权限下的人员
        Integer dataPermission = userModel.getDataPermission(userEntity, SaasMarkEnum.SAAS, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode(), null);
        List<String> userIdIn = userModel.getSubIdListByDataPermission(dataPermission, userEntity.getUserId(), userEntity.getCorpid(), BasicConstant.ONE, false);
        List<String> teamUserIdList = new ArrayList<>();
        JSONArray ownerId = data.getJSONArray(TabConstant.OWNERID);
        JSONArray coUserId = data.getJSONArray(TabConstant.COUSERID);
        if(CollectionUtils.isNotEmpty(ownerId)){
            List<String> collect = ownerId.stream().map(v -> (String) v).collect(Collectors.toList());
            teamUserIdList.addAll(collect);
        }
        if(CollectionUtils.isNotEmpty(coUserId)){
            List<String> collect = coUserId.stream().map(v -> (String) v).collect(Collectors.toList());
            teamUserIdList.addAll(collect);
        }
        return CollectionUtils.intersection(teamUserIdList, userIdIn).size() > 0;
    };

    @Override
    public PaasFormEntityExt getForm(FormDataDetailDTO formDataDetailDTO, PaasFormDataEntityExt paasFormDataEntityExt, String corpid) throws XbbException {
        Long formId = paasFormDataEntityExt.getFormId();
        PaasFormEntityExt paasFormEntityExt = paasFormModel.getByKey(paasFormDataEntityExt.getFormId(), corpid);
        Integer businessType = paasFormEntityExt.getBusinessType();
        Long appId = paasFormEntityExt.getAppId();
        Long menuId = paasFormEntityExt.getMenuId();
        if (Objects.nonNull(paasFormEntityExt)) {
            Integer saasMark = paasFormEntityExt.getSaasMark();
            Integer distributorMark = paasFormEntityExt.getDistributorMark();
            formDataDetailDTO.setDistributorMark(distributorMark);
            formDataDetailDTO.setBusinessType(businessType);
            formDataDetailDTO.setSaasMark(paasFormEntityExt.getSaasMark());
            // 把distributorMark再放进去
            TransmittableThreadLocalUtil.setValue(saasMark, formDataDetailDTO.getBusinessType(), menuId, distributorMark);
            if (Objects.equals(distributorMark, DistributorMarkEnum.DISTRIBUTOR.getCode())) {
                boolean enable = paasAppModel.validateAppEnable(null, XbbRefTypeEnum.DISTRIBUTOR.getAlias(), SaasMarkEnum.SAAS.getCode(), corpid);
                if (!enable) {
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.DISTRIBUTOR_DISABLE);
                }
            }
        }
        if (Objects.nonNull(paasFormEntityExt) && Objects.equals(paasFormEntityExt.getDistributorMark(), DistributorMarkEnum.DISTRIBUTOR.getCode())) {
            paasFormDataEntityExt.setAppId(paasFormEntityExt.getAppId());
            paasFormDataEntityExt.setMenuId(paasFormEntityExt.getMenuId());
            businessType = XbbRefTypeEnum.transferBusinessType4Distributor(formDataDetailDTO.getBusinessType(), DistributorMarkEnum.DISTRIBUTOR.getCode());
            formDataDetailDTO.setBusinessType(businessType);
            formDataDetailDTO.setSubBusinessType(businessType);
        }
        if (RedundantTemplateTypeEnum.isMultiTemplate(businessType)) {
            if ( Objects.equals(paasFormEntityExt.getEnable(), 0) || Objects.equals(paasFormEntityExt.getDel(), 1) ) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100017);
            }
            paasFormModel.validateByPermission(paasFormEntityExt, formDataDetailDTO.getLoginUser());
        }
        //校验应用是否开启
        Boolean appEnable = paasAppModel.validateAppEnable(appId, "", null, corpid);
        if (!appEnable ) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.APP_NOT_ENABLE);
        }
        //校验菜单是否开启
        PaasMenuEntity paasMenuEntity = paasMenuModel.getByKey(menuId, corpid);
        if ( Objects.nonNull(paasMenuEntity) && Objects.equals(0, paasMenuEntity.getEnable()) ) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.MENU_NOT_ENABLE);
        }

        return paasFormEntityExt;
    }

    @Override
    public PaasFormDataEntityExt getData(Integer businessType, Integer subBusinessType, Integer saasMark, String corpid, Long dataId, Long formId) throws XbbException {
        PaasFormDataEntityExt paasFormDataEntityExt = proFormDataHelp.getFormDataExt(corpid, saasMark, businessType, dataId);
        if (Objects.isNull(paasFormDataEntityExt)) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_DATA_NOT_EXIST);
        }
        FormDataUtil.checkData(paasFormDataEntityExt, subBusinessType);

        return paasFormDataEntityExt;
    }


    @Override
    public List<FieldAttrEntity> getExplainList(PaasFormEntityExt form, String corpid) throws XbbException {
        PaasFormExplainEntity paasFormExplainEntity = paasFormExplainModel.getByFormId(form.getId(), corpid);
        return JSON.parseArray(paasFormExplainEntity.getExplains(), FieldAttrEntity.class);
    }

    @Override
    public String dealWebDetailLabelListLocation(FormDataDetailDTO formDataDetailDTO, PaasFormEntityExt form, JSONArray tags, PaasFormDataEntityExt paasFormDataEntityExt, Map<String, FieldAttrEntity> explainMap) throws XbbException {
        JSONArray labelList = JSONArray.parseArray(form.getLabels());
        return labelHelp.dealWebDetailLabelListLocation(formDataDetailDTO, labelList,tags, paasFormDataEntityExt, explainMap);
    }

    @Override
    public String dealAppDetailLabelListLocation(FormDataDetailDTO formDataDetailDTO, PaasFormEntityExt formEntity, List<SummaryDataPoJo> labelList, PaasFormDataEntityExt paasFormDataEntityExt, Map<String, FieldAttrEntity> explainMap) throws XbbException {
        return labelHelp.dealAppDetailLabelListLocation(formDataDetailDTO, labelList, paasFormDataEntityExt, explainMap);
    }

    @Override
    public MobileDetailSpecialInfoPojo getMobileDetailSpecialInfo(FormDataDetailDTO formDataDetailDTO, PaasFormDataEntityExt paasFormDataEntityExt, Map<String, FieldAttrEntity> explainMap) throws XbbException {
        JSONObject data = paasFormDataEntityExt.getData();
        String corpid = formDataDetailDTO.getCorpid();
        UserVO loginUser = formDataDetailDTO.getLoginUser();
        Integer businessType = formDataDetailDTO.getBusinessType();
        String userId = loginUser.getUserId();
        Long dataId = paasFormDataEntityExt.getId();
        List<MobileDetailScriptPojo> scriptPojoList = getDetailShowScript(businessType, loginUser,paasFormDataEntityExt, explainMap);
        MobileDetailStatusPojo mobileDetailStatusPojo = getDetailShowStatus(businessType, data);
        Map<String, Object> operationList = getDetailShowOperation(corpid, userId, businessType, dataId, data);

        MobileDetailSpecialInfoPojo mobileDetailSpecialInfoPojo = new MobileDetailSpecialInfoPojo();
        mobileDetailSpecialInfoPojo.setScript(scriptPojoList);
        mobileDetailSpecialInfoPojo.setStatus(mobileDetailStatusPojo);
        mobileDetailSpecialInfoPojo.setOperation(operationList);

        return mobileDetailSpecialInfoPojo;
    }


    @Override
    public List<SummaryDataPoJo> getSummaryList(FormDataDetailDTO formDataDetailDTO, PaasFormDataEntityExt formData, PaasFormEntityExt formEntity, List<FieldAttrEntity> list, Map<String, FieldAttrEntity> explainMap, JSONObject data) throws XbbException {

        return ExplainUtil.getSpecialSummaryList(formEntity.getSummaryList(), data, explainMap, formData);
    }

    @Override
    public List<SummaryDataPoJo> getLabelList(FormDataDetailDTO formDataDetailDTO, PaasFormDataEntityExt formData, PaasFormEntityExt formEntity, List<FieldAttrEntity> list, Map<String, FieldAttrEntity> explainMap, JSONObject data) throws XbbException {
        // 解析标签
        return ExplainUtil.getSpecialSummaryList(formEntity.getLabelsList(), data, explainMap, formData);
    }

    @Override
    public List<FormTitlePoJo> getTitleList(FormDataDetailDTO formDataDetailDTO, PaasFormDataEntityExt formData, PaasFormEntityExt formEntity, List<FieldAttrEntity> list, Map<String, FieldAttrEntity> explainMap, JSONObject data) throws XbbException {

        return ExplainUtil.getSpecailFormTitle(JSONArray.parseArray(formEntity.getCustomTitle()), explainMap, data, list, formData);
    }
    /**
     * 判断该用户是否拥有详情页面查看权限
     * @param businessType 业务类型
     * @param loginUser 用户权限
     * @param flowStatus
     * @param saasMark
     * @param menuId
     * @throws XbbException
     */
    protected void verifyQueryPermission(Integer businessType, UserVO loginUser, Integer saasMark, Long menuId, Integer flowStatus) throws XbbException{

        // 查看权限校验
        VerifyViewPermissionDTO verifyViewPermissionDTO = new VerifyViewPermissionDTO(  saasMark, businessType, menuId, loginUser);
        ProPermissionHelp.verifyQueryPermission(verifyViewPermissionDTO);
        //审批中数据不让看，直接报错，目前这样处理，后续优化为可见，但没有任何操作权限
        if ( FlowStatusEnum.inApproval(flowStatus) ) {
            throw new XbbException(BuinessDefaultErrorCodeEnum.API_ERROR_200023);
        }
    }

    @Override
    public void handleDetailSpecialField(PaasFormDataEntityExt formData, JSONObject data, Map<String, FieldAttrEntity> explainMap, HandlerExplainDTO handlerExplainDTO) throws XbbException {

    }

    @Override
    public DataDetailPojo handleDetailData(Integer businessType, PaasFormDataEntityExt formData, String userId, HandlerExplainDTO handlerExplainDTO) throws XbbException {
        DataDetailPojo dataDetailPojo = new DataDetailPojo();
        // 外链
        Integer outerLinkShare = setOuterLinkShare(handlerExplainDTO.getCorpid(), formData.getFormId());
        dataDetailPojo.setHasOuterLinkShare(outerLinkShare);
        return dataDetailPojo;
    }


    protected List<MobileDetailScriptPojo> setDetailShowScript(PaasFormDataEntityExt paasFormDataEntityExt, Integer businessType, JSONObject data, Map<String, FieldAttrEntity> explainMap, String attr) {
        Boolean invisible = false;
        try {
            String corpid = paasFormDataEntityExt.getCorpid();
            Long dataId = paasFormDataEntityExt.getId();
            Map<Long, List<String>> mainUserMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            Map<Long, List<String>> coUserMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            //协同团队
            formDataFormExplainHelper.getUserIdMap(Collections.singletonList(dataId), corpid, businessType, false, mainUserMap, coUserMap);
            HandlerExplainDTO handlerExplainDTO = new HandlerExplainDTO();
            //BeanUtil.copyProperties(businessProductListDTO, handlerExplainDTO);
            handlerExplainDTO.setCreatorId(paasFormDataEntityExt.getCreatorId());
            handlerExplainDTO.setOwnerId(mainUserMap.getOrDefault(dataId, new ArrayList<>()));
            handlerExplainDTO.setCoUserId(coUserMap.getOrDefault(dataId, new ArrayList<>()));
            handlerExplainDTO.setExplainList(new ArrayList<>(explainMap.values()));
            FieldAttrEntity fieldAttrEntity = explainMap.get(attr);
            if (Objects.nonNull(fieldAttrEntity)) {
                invisible = ExplainUtil.isFieldNeedHide(fieldAttrEntity, handlerExplainDTO);
            }
        } catch (Exception e) {
            invisible = false;
        }
        List<MobileDetailScriptPojo> scriptPojoList = new ArrayList<>();
        FieldAttrEntity attrEntity = explainMap.get(attr);
        if (Objects.nonNull(attrEntity)) {
            MobileDetailScriptPojo pojo = new MobileDetailScriptPojo();
            Object moneyStr = AttrDecimalPrecisionHelper.moneyParseThrousandth(attrEntity,data,attr);
            if (invisible) {
                moneyStr = StringConstant.INVISIBLE_VALUE;
            }
            if (Objects.nonNull(moneyStr)) {
                pojo.setMoneyScript(moneyStr + UnitEnum.MONEY.getName());
                scriptPojoList.add(pojo);
            }
        }
        return scriptPojoList;
    }

    @Override
    public List<TopPermissionsPoJo> getMobileDetailBottomOperation(HandelDetailPojo handelDetailPojo, PaasFormEntityExt formEntity, PaasFormDataEntityExt formData, HandlerExplainDTO handlerExplainDTO, Map<String, FieldAttrEntity> explainMap) throws XbbException {
        Integer businessType = handelDetailPojo.getBusinessType();
        Integer businessType4Distributor = XbbRefTypeEnum.transferBusinessType4Distributor(businessType, handelDetailPojo.getDistributorMark());
        UserVO userVO = handelDetailPojo.getLoginUser();
        Integer distributorMark = handelDetailPojo.getDistributorMark();
        List<MobileDetailBottomOperationEnum> bottomOperationEnumList = MobileDetailBottomOperationEnum.getByBusinessTypeAndPermission(businessType4Distributor, userVO.getPermSet());
        List<TopPermissionsPoJo> bottomOperationList = new ArrayList<>();
        for (MobileDetailBottomOperationEnum anEnum : bottomOperationEnumList) {
            TopPermissionsPoJo topPermissionsPoJo = new TopPermissionsPoJo();
            BeanUtil.copyProperties(anEnum, topPermissionsPoJo);
            topPermissionsPoJo.setDistributorMark(distributorMark);
            bottomOperationList.add(topPermissionsPoJo);
        }
        return bottomOperationList;
    }

    @Override
    public void returnVO(PaasFormEntityExt formEntity, PaasFormDataEntityExt formData, MobileFormCommonDetailVO mobileFormCommonDetailVO, String userId) throws XbbException {
        mobileFormCommonDetailVO.setHasOuterLinkShare(setOuterLinkShare(formEntity.getCorpid(), formEntity.getId()));
        mobileFormCommonDetailVO.setDistributorMark(formEntity.getDistributorMark());
        mobileFormCommonDetailVO.setPaasFormEntity(formEntity);

    }

    @Override
    public List<DetailTabPojo> handleDetailTab(HandelDetailPojo handelDetailPojo, PaasFormEntityExt formEntity, PaasFormDataEntityExt paasFormDataEntityExt, Map<String, FieldAttrEntity> explainMap, HandlerExplainVO handlerExplainVO, HandlerExplainDTO handlerExplainDTO) throws XbbException {
        Integer businessType = handelDetailPojo.getBusinessType();
        UserVO userVO = handelDetailPojo.getLoginUser();
        List<DetailTabPojo> tabPojoList = new ArrayList<>();
        String corpid = paasFormDataEntityExt.getCorpid();
        String userId = userVO.getUserId();
        List<BusinessDetailTabEnum> tabEnumList;
        String platFormEnum = handlerExplainDTO.getPlatform();
        if (Objects.equals(platFormEnum, PlatFormEnum.WEB.getValue())) {
            tabEnumList = BusinessDetailTabEnum.getByBusinessTypeAndPermission(businessType, userVO.getPermSet());
        } else {
            tabEnumList = BusinessDetailTabEnum.getByBusinessTypeAndPermissionForDingtalk(businessType, userVO.getPermSet());
        }

        // 获取对应businessType的alias
        List<String> aliasIn = BusinessDetailTabEnum.getAliasIn(tabEnumList);

        // 记录businessType与menuName的关系
        Map<Integer, String> paasBusinessTypeToName = paasMenuModel.getMenuNameByAlias(aliasIn, corpid, businessType);

        //协同团队
        Map<Long, List<String>> mainUserMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        Map<Long, List<String>> coUserMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        formDataFormExplainHelper.getUserIdMap(Collections.singletonList(paasFormDataEntityExt.getDataId()),corpid,businessType,false,mainUserMap,coUserMap);

        // 当前数据的创建人、负责人、协同人、当前操作人
        handlerExplainDTO.setLoginUser(userVO);
        handlerExplainDTO.setUserId(userId);
        handlerExplainDTO.setOwnerId(mainUserMap.get(paasFormDataEntityExt.getDataId()));
        handlerExplainDTO.setCoUserId(coUserMap.get(paasFormDataEntityExt.getDataId()));
        handlerExplainDTO.setCreatorId(paasFormDataEntityExt.getCreatorId());

        for (BusinessDetailTabEnum tabEnum : tabEnumList) {
            if (Objects.equals(tabEnum.getAnEnum().getKey(), DetailTabEnum.CONTRACT_COMPARE.getKey()) && !contractCompareUtil.showCompareTab(corpid, handelDetailPojo.getLoginUser().getPermSet(), userVO.getUserId())) {
                continue;
            }
            DetailTabPojo detailTabPojo = new DetailTabPojo();
            BeanUtil.copyProperties(tabEnum.getAnEnum(), detailTabPojo);
            changeTabEnumName(paasBusinessTypeToName, tabEnum, detailTabPojo);
            detailTabPojo.setAttr(detailTabPojo.getKey());
            tabPojoList.add(detailTabPojo);
        }
        handleTeamTab(tabPojoList, explainMap);
        List<LinkListPojo> linkList = JSONArray.parseArray(formEntity.getAssociationList(), LinkListPojo.class);
        handlerExplainVO.setAppId(formEntity.getAppId());
        handlerExplainVO.setFormId(formEntity.getId());
        // 公共tab
        tabPojoList.addAll(linkListService.commonTab(corpid, userVO, handlerExplainVO, handlerExplainDTO, businessType, paasFormDataEntityExt.getDel(), linkList));
        // tab排序
        tabPojoList = detailTabConfigService.handleDetailTabSort(userVO.getUserId(), corpid, handlerExplainVO.getFormId(), businessType, tabPojoList);
        return tabPojoList;
    }

    /**
     *
     * @param formDataDetailDTO
     * @param corpid
     * @param paasFormDataEntityExt
     * @return java.lang.String
     * @author 吴峰
     * @date 2022/2/16 21:31
     * @throws XbbException
     */
    protected String getPid(FormDataDetailDTO formDataDetailDTO, String corpid, PaasFormDataEntityExt paasFormDataEntityExt) {
        try {
            // 满足条件精线索可用才能跳转到第三方（精线索）页面
            if ( fineClueHelp.isFineClueByCorpid(formDataDetailDTO.getCorpid(), formDataDetailDTO.getBusinessType(), formDataDetailDTO.getDistributorMark())) {
                //搜客/工商查询老用户
                String pid = fineClueHelp.getPidByCompanyName(corpid, paasFormDataEntityExt.getData().getString(CustomerManagementEnum.NAME.getAttr()), formDataDetailDTO.getPlatform());
                if (Objects.nonNull(pid)) {
                    return pid;
                } else if (Objects.equals(formDataDetailDTO.getBusinessType(), XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode())) {
                    // saas头部栗子详情页(开启搜客或者工商后提供)
                    return searchCustomerService.handelDetailClue(paasFormDataEntityExt);
                }
                return null;
            }
        } catch (Exception e) {
            LOGGER.info("工商查询没有查询到该公司");
        }
        return null;
    }

    @Override
    public void analysisGetOfThousandBits(JSONObject data, List<FieldAttrEntity> explainList, Boolean analysisAmountOfThousandBitsWithOriginalValue) throws XbbException {
        // 千分位换算
        formDataGetAnalysisDataHelp.analysisGetOfThousandBits(data, explainList, analysisAmountOfThousandBitsWithOriginalValue);
    }
}
